package main

//简单演示go操作mongo的，curd，condition
import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)

const (
	mongoUri = "mongodb://10.70.30.73:27018"
)

//注意别名需要用""引号括起来
type timePoint struct {
	StartTime int64 `bson:"start_time"`
	EndTime   int64 `bson:"end_time"`
}

type docJobLog2 struct {
	//如果不指定后面的``标签内容，将会把字段名称变为小写，此处写json无效，
	Name         string    `json:"name"`
	Command      string    `json:"command"`
	RelationTime timePoint `json:"relation_time"`
	Err          string    `json:"error"`
	ExecResult   string    `json:"exec_result"`
}

type docJobLog struct {
	//如果不指定后面的``标签内容，将会把字段名称变为小写，此处写json无效，
	Name         string    `bson:"name"`
	Command      string    `bson:"command"`
	RelationTime timePoint `bson:"relation_time"`
	Err          string    `bson:"error"`
	ExecResult   string    `bson:"exec_result"`
}

func main() {

	var (
		insertResult     *mongo.InsertOneResult
		insertManyResult *mongo.InsertManyResult
		insertId         interface{} //默认为mongo的object_id
		err              error

		//interface,可以理解为void*【空指针】，java Object对象，指针是无类型的，可以指向任意的内存地址空间，至于指向的内存地址是什么类型，interface会在里面记录一个type，这个type关联一个指针，而这个指针指向了具体的类型。都可以进行向下转型。
		docMany []interface{}
	)

	client, err := mongo.NewClient(options.Client().ApplyURI(mongoUri))
	err = client.Connect(context.TODO())
	if err != nil {
		fmt.Println(err)
	}
	database := client.Database("my_db")
	collection := database.Collection("my_collection")

	doc1 := &docJobLog2{
		Name:    "hi",
		Command: "echo hi",
		RelationTime: timePoint{
			StartTime: time.Now().Unix(),
			EndTime:   time.Now().Unix() + 2,
		},
		Err:        "",
		ExecResult: "",
	}
	doc2 := &docJobLog2{
		Name:    "he",
		Command: "echo he",
		RelationTime: timePoint{
			StartTime: time.Now().Unix(),
			EndTime:   time.Now().Unix() + 2,
		},
		Err:        "",
		ExecResult: "",
	}
	//此处插入的第二个参数为interface{},可理解为void*,或者java中的object.mongo内部会把传递的类型序列化为bson结构。
	//返回值为一个insert result的指针,InsertedID为一个interface类型，转换为string，但是会有错误输出 panic: interface conversion: interface {} is primitive.ObjectID, not string
	insertResult, err = collection.InsertOne(context.TODO(), doc2)

	//返回的id为mongo的默认全局唯一id，snowflake
	fmt.Printf(insertResult.InsertedID.(primitive.ObjectID).Hex())

	//批量插入,第二个{}为初始化列表
	docMany = []interface{}{
		doc1,
		doc2,
	}
	insertManyResult, err = collection.InsertMany(context.TODO(), docMany)

	//fmt.Println("插入多头数据结果为,", insertManyResult.InsertedIDs)

	for _, insertId = range insertManyResult.InsertedIDs {

		fmt.Println(insertId.(primitive.ObjectID).Hex())
	}

}
